package com.lds.management.center.common.util;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    public static String toJson(Object o) {
        if (Objects.isNull(o)) return null;
        try {
            return mapper.writeValueAsString(o);
        } catch (Exception e) {
            log.info("toJson error. cause={}", e.getMessage());
            return null;
        }
    }

    public static <T> T fromJson(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json) || Objects.isNull(tClass)) return null;
        try {
            return mapper.readValue(json, tClass);
        } catch (Exception e) {
            log.info("fromJson[tClass] error. cause={}", e.getMessage());
            return null;
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(json) || Objects.isNull(typeReference)) return null;
        try {
            return mapper.readValue(json, typeReference);
        } catch (Exception e) {
            log.info("fromJson[typeReference] error. cause={}", e.getMessage());
            return null;
        }
    }

    public static <T> List<T> fromJsonList(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json) || Objects.isNull(tClass)) return null;
        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
        try {
            return mapper.readValue(json, listType);
        } catch (IOException e) {
            log.info("fromJsonList error. cause={}", e.getMessage());
            return null;
        }
    }

}
